<%@ page import="com.party.core.model.system.TargetType" %>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="../include/tag.jsp"%>
<!DOCTYPE html>
<html lang="zh">
<head>
<title>添加人员</title>
<%@include file="../include/commonFile.jsp"%>
<link rel="stylesheet" href="${ctx}/css/common/list.css">
<link rel="stylesheet" href="${ctx}/css/common/form.css">
<link rel="stylesheet" href="${ctx}/css/ui/circle/add_cmember.css">
<link rel="stylesheet" href="${ctx}/css/ui/system/member/member_form.css">
</head><body>
<!--头部-->
<%@include file="../include/header.jsp"%>
<div class="index-outside">
	<%@include file="../include/sidebar.jsp"%>
	<!--内容-->
	<section>
		<div class="section-main">

			<!-- 正文请写在这里 -->
			<form id="infoForm" class="layui-form mt20" method="post" action="${ctx}/competition/member/saveMember.do">
				<input type="hidden" name="projectId" value="${project.id}" />
				<input type="hidden" name="groupId" value="${group.id}" />
				<input type="hidden" name="memberId" id="memberId" />
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">真实姓名<span class="f-verify-red">*</span></label>
						<div class="layui-input-inline">
							<input class="layui-input typeahead" name="realname" lay-verify="realname" placeholder="真实姓名" id="realName" autocomplete="off"  type="text"/>
						</div>
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">头像<span class="f-verify-red">*</span></label>
					<div class="cover-content">
						<input type="hidden" name="logo" id="pic" lay-verify="pic" />
						<span id="cover-img" class="round-img" style="background-image:url(${ctx}/image/avatar1.png)"></span>
						<a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加头像</a>
					</div>
				</div>
				<div class="layui-form-item">
	         		<div class="layui-inline">
	              		<label class="layui-form-label">性别</label>
	                  	<div class="layui-input-inline">
	                      	<input type="radio" name="sex" value="1" title="男">
	                      	<input type="radio" name="sex" value="0" title="女">
	                  	</div>
	              	</div>
		     	</div>
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">手机号<span class="f-verify-red">*</span></label>
						<div class="layui-input-inline">
							<input name="mobile" lay-verify="mobile" class="layui-input typeahead" id="phone" autocomplete="off" type="text">
						</div>
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">公司</label>
						<div class="layui-input-inline">
							<input type="text" name="company" class="layui-input" id="company">
						</div>
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">职位</label>
						<div class="layui-input-inline">
							<input type="text" name="jobTitle" class="layui-input" id="jobTitle">
						</div>
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">行业</label>
						<div class="layui-input-inline">
							<select lay-verify="industryParent" lay-filter="industryParent" id="inParent">
								<option value="">选择行业分类</option>
								<c:forEach var="industry" items="${industries}">
									<option value="${industry.id}">${industry.name}</option>
								</c:forEach>
							</select>
						</div>
						<div class="layui-input-inline">
							<select name="industry" lay-verify="industry" id="industry">
								<option value="">选择行业</option>
							</select>
						</div>
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">城市</label>
						<div class="layui-input-inline">
							<select lay-verify="province" lay-filter="province" id="arParent">
								<option value="">选择省份/直辖市</option>
								<c:forEach var="area" items="${areas}">
									<option value="${area.id}">${area.name}</option>
								</c:forEach>
							</select>
						</div>
						<div class="layui-input-inline">
							<select name="city" lay-verify="city" id="city">
								<option value="">选择城市</option>
							</select>
						</div>
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-input-block">
						<a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="infoForm" id="saveMember">立即提交</a>
						<a href="javascript:addMember()" class="layui-btn layui-btn-danger" id="addMember" style="display: none; margin-left: 0px">立即提交</a>
						<c:if test="${not empty project.id && empty group.id}">
							<a href="${ctx}/competition/member/list.do?projectId=${project.id}" class="layui-btn layui-btn-primary">取消</a>
						</c:if>
						<c:if test="${not empty group.id}">
							<a href="${ctx}/competition/member/list.do?pGroupId=${group.id}" class="layui-btn layui-btn-primary">取消</a>
						</c:if>
					</div>
				</div>
			</form>
		</div><!--底部-->
		<%@include file="../include/footer.jsp"%>
	</section>
</div>

<script type="text/javascript" src="${ctx}/script/common/list.js"></script>
<script type="text/javascript" src="${ctxStatic}/typeahead/typeahead.bundle.js"></script>
<script>
    var thMember = {}, thSel=false;
	var form = null;

	$(function() {
        layui.use([ 'form', 'laydate', 'element' ], function() {
            form = layui.form, laydate = layui.laydate, element = layui.element;

            form.verify({
                fullname : function(value) {
                    if (value == "") {
                        return '请输入真实姓名';
                    }
                },
                realname : function(value) {
                    if (value == "") {
                        return '请输入昵称';
                    }
                },
                pic : function(value) {
                    if (value == "") {
                        return "请上传头像";
                    }
                },
                mobile : function(value) {
                    if (value == "") {
                        return "手机号必须填写";
                    } else if (value != "" && !util.checkMobile(value)) {
                        return "请填写正确格式的手机号码";
                    } else if (value != "" && util.checkMobile(value)) {
                        var isRepeat = txz.checkIsUnique('mobile', value, '', 1);
                        if (undefined == isRepeat) {
                            return "验证手机号异常";
                        } else if (isRepeat) {
                            return "手机号已存在";
                        }
                    }
                }
            });

            //监听提交
            form.on('submit(infoForm)', function (data) {
                txz.submitObject(data.elem, function (callBack) {
                    var action = $("#infoForm").attr("action");
                    $.post(action, $('#infoForm').serialize(), function (res) {
                        typeof callBack === 'function' && callBack();
                        if (res.success) {
                            util.layerMsgSuccess("提交成功", function () {
                                if ('${project.id}' != "" && '${group.id}' == "") {
                                    location.href = "${ctx}/competition/member/list.do?projectId=${project.id}";
                                } else if ('${group.id}' != "") {
                                    location.href = "${ctx}/competition/member/list.do?pGroupId=${group.id}";
                                }
                            });
                        } else {
                            util.layerMsgError("提交失败")
                        }
                    });
                });
                return false;
            });

            // 城市
            form.on('select(province)', function(data) {
                $("#city").html("");
                var cityId = data.value;
                loadCityData(cityId, '');
            });

            // 行业
            form.on('select(industryParent)', function(data) {
                $("#industry").html("");
                var industryId = data.value;
                loadIndustryData(industryId, '');
            });

        });
        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                type: '<%=TargetType.LOGO.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        })
        $('#realName').typeahead({
            hint: false,
            highlight: true,
            minLength: 1
        },{
            name: 'realname',
            display: 'realname',
            async: true,
            templates: {
                suggestion: function (member) {
                    return '<a href="javascript:void(0);"><span data-id="' + member.id + '" class="t-user-logo" style="background-image: url(' + member.logo
                        + '),url(${ctx}/image/def_user_logo.png)"></span><span class="t-user-name">' +  (member.realname||'') + '</span></a>';
                }
            },
            source: function (q, syn, aja) {
                _findMember('realName',q,aja);
            }
        });

        $('#phone').typeahead({
            hint: false,
            highlight: true,
            minLength: 1
        },{
            name: 'phone',
            display: 'mobile',
            async: true,
            templates: {
                suggestion: function (member) {
                    return '<a href="javascript:void(0);"><span data-id="' + member.id + '" class="t-user-logo" style="background-image: url(' + member.logo
                        + '),url(${ctx}/image/def_user_logo.png)"></span><span class="t-user-name">' +  (member.realname||'') +(member.mobile||'') +'</span></a>';
                }
            },
            source: function (q, syn, aja) {
                _findMember('phone',q,aja);
            }
        });
        $('.typeahead').bind('typeahead:select', function(ev, suggestion) {
            console.log(suggestion);
            thMember = suggestion;
            thSel = true;
            $(ev.currentTarget).blur();
        });
        $('.typeahead').blur(function(){
            var type = $(this).prop('id');
            if(thSel){
                _fillInfoById(type,thMember.id || '');
            }else{
                if(thMember.id){
                    thMember = {};
                    clearForm(type);
                }
            }
            thSel = false;
        });

        function _findMember(type,q, cb) {
            $.ajax({
                url : "${ctx}/system/member/findMemberByPhoneOrName.do",
                type : "post",
                dataType : "json",
                data : {
                    property : type,
                    value : q
                },
                success : function(ret) {
                    cb(ret.data);
                }
            });
        }
        function _fillInfoById(type,id) {
            $.ajax({
                url : '${ctx}/system/member/getMember.do',
                type : 'POST',
                dataType : 'JSON',
                data : {
                    id : id
                },
                success : function(ret) {
                    var member = ret.data.member;
                    var inParent = ret.data.inParent;
                    var arParent = ret.data.arParent;
                    $("#infoForm").find("input[type=text]").prop("disabled", true);
                    $("#infoForm").find("select").prop("disabled", true);

                    if(type == "realName"){
                        $("#phone").prop("disabled",true);
                        $("#realName").prop("disabled",false);
                    } else if(type == "phone"){
                        $("#phone").prop("disabled",false);
                        $("#realName").prop("disabled",true);
                    }

                    var logo = member.logo || '';
                    var realname = member.realname || '';
                    var phone = member.mobile || '';
                    var company = member.company || '';
                    var jobTitle = member.jobTitle || '';
                    var cityId = member.city || '';
                    var industryId = member.industry || '';
                    $("#cover-img").css('background-image', "url('" + logo + "')");
                    $("#realName").val(realname);
                    $("#phone").val(phone);
//                    $("input[name=sex]").val(member.sex);
                    $("#company").val(company);
                    $("#jobTitle").val(jobTitle);
                    $("#inParent").val(inParent);
                    $("#arParent").val(arParent);
                    $("#memberId").val(member.id);
                    $("input[name=sex]").prop("disabled", true);
					$("input[name=sex][value="+member.sex+"]").prop('checked','checked');

                    loadCityData(arParent, cityId);
                    loadIndustryData(inParent, industryId);

                    $(".u-single-upload").hide();

                    $("#addMember").show();
                    $("#saveMember").hide();
                    form.render('select');
                    form.render('radio');
                }
            });
        }

	})
	
	// 联动城市
	function loadCityData(arParent, cityId) {
		var array = new Array();
		if (arParent == "") {
			$("#city").html("");
			array.push("<option value=''>选择城市</option>");
			$("#city").append(array.join(""));
			form.render('select');
		} else {
			$.post("${ctx}/system/member/getCityByParentId.do", {
				"cityId" : arParent
			}, function(data) {
				for (var i = 0; i < data.length; i++) {
					if (cityId == data[i].id) {
						array.push("<option value = '" + data[i].id + "' selected='selected'>" + data[i].name + "</option>");
					} else {
						array.push("<option value = '" + data[i].id + "'>" + data[i].name + "</option>");
					}
				}
				$("#city").append(array.join(""));
				form.render('select');
			});
		}
	}

	// 联动行业
	function loadIndustryData(inParent, industryId) {
		var array = new Array();
		if (inParent == "") {
			$("#industry").html("");
			array.push("<option value=''>选择行业</option>");
			$("#industry").append(array.join(""));
			form.render('select');
		} else {
			$.post("${ctx}/system/member/getIndustryByParentId.do", {
				"industryId" : inParent
			}, function(data) {
				for (var i = 0; i < data.length; i++) {
					if (industryId == data[i].id) {
						array.push("<option value = '" + data[i].id + "' selected='selected' >" + data[i].name + "</option>");
					} else {
						array.push("<option value = '" + data[i].id + "'>" + data[i].name + "</option>");
					}
				}
				$("#industry").append(array.join(""));
				form.render('select');
			});
		}
	}

    function clearForm(type) {
        $("#infoForm").find("input[type=text]").prop("disabled", false);
        $("#infoForm").find("input[type=radio]").prop("disabled", false);
        $("#infoForm").find("select").removeAttr("disabled");
        $("#infoForm").find("select").find("option:eq(0)").prop("selected", true);
        if(type == 'realName'){
            $("#infoForm").find("input[type=text]:not(#realName)").val("");
        }else if(type == 'phone'){
            $("#infoForm").find("input[type=text]:not(#phone)").val("");
        }
        $("#memberId").val("");
        $(".u-single-upload").show();
        $("#addMember").hide();
        $("#saveMember").show();
        $("#cover-img").css('background-image', "url(${ctx}/image/avatar1.png");
        $("#city").html("<option value=''>选择城市</option>");
        $("#industry").html("<option value=''>选择行业</option>");
        form.render('select');
        form.render('radio');
    }
	// 添加成员
	function addMember() {
		$.post('${ctx}/competition/member/saveMember.do', {
			projectId : '${project.id}',
			groupId : '${group.id}',
			memberId : $("#memberId").val()
		}, function(res) {
			if (res.success) {
				util.layerMsgSuccess('添加成功', function() {
					if ('${project.id}' != "" && '${group.id}' == "") {
						location.href = "${ctx}/competition/member/list.do?projectId=${project.id}";
					} else if ('${group.id}' != "") {
						location.href = "${ctx}/competition/member/list.do?pGroupId=${group.id}";
					}
				});
			} else {
                util.layerMsgError("添加失败")
			}
		});
	}
</script>
<script type="text/javascript">
    <c:if test="${not empty project.id && empty group.id}">
    txz.initHeader({
        nav:[{
            name: '赛事项目管理',
            href: '${ctx}/competition/project/list.do'
        },{
            name: '${project.title}',
            curr: true
        },{
            name: '人员管理',
            href: '${ctx}/competition/member/list.do?projectId=${project.id}'
        },{
            name: '添加人员',
            curr: true
        }],
        btns:[{
            name: '返回',
            href: '${ctx}/competition/member/list.do?projectId=${project.id}',
            icon: 'back'
        }]
    });
    </c:if>
    <c:if test="${not empty group.id}">
    txz.initHeader({
        nav:[{
            name: '赛事项目管理',
            href: '${ctx}/competition/project/list.do'
        },{
            name: '${project.title}',
            curr: true
        },{
            name: '${group.groupName}',
            curr: true
        },{
            name: '人员管理',
            href: '${ctx}/competition/member/list.do?pGroupId=${group.id}'
        },{
            name: '添加人员',
            curr: true
        }],
        btns:[{
            name: '返回',
            href: '${ctx}/competition/member/list.do?pGroupId=${group.id}',
            icon: 'back'
        }]
    });
    </c:if>
</script>
</body>
</html>